#include "dtwentyitemcontainer.h"


DTwentyItemContainer::DTwentyItemContainer(QObject *parent) :
    DTwentyItem(parent),
    d(new Data())
{
}

DTwentyItemContainer::DTwentyItemContainer(const DTwentyItemContainer &other) :
    DTwentyItem(other),
    d(other.d)
{
}

int DTwentyItemContainer::type() const
{
    return qMetaTypeId<DTwentyItemContainer*>();
}


bool DTwentyItemContainer::removable() const
{
    return false;
}

int DTwentyItemContainer::childType() const
{
    return d->childType;
}

QString DTwentyItemContainer::childTypeName() const
{
    QString ret = QMetaType::typeName(childType());
    if (ret.endsWith("*"))
    {
        ret = ret.remove("*");
    }
    return ret;
}

DTwentyItem *DTwentyItemContainer::newChild(const QString &name)
{
    if (d->childType <= QMetaType::User)
    {
        qDebug() << Q_FUNC_INFO << "Meta type is invalid!";
        return 0;
    }

    const QMetaObject* mo = QMetaType::metaObjectForType(d->childType);
    if (!mo)
    {
        return 0;
    }

    DTwentyItem* item = qobject_cast<DTwentyItem*>(mo->newInstance());
    item->setParent(this);
    if (!name.isEmpty())
    {
        item->setName(name);
    }
    else
    {
        item->setName(childTypeName());
    }

    return item;
}

QVariantMap DTwentyItemContainer::valueOptions() const
{
    if (d->valueSource.isNull())
    {
        return QVariantMap();
    }

    QVariantMap ret;
    foreach (DTwentyItem* item, d->valueSource->findChildren<DTwentyItem*>(QString(), Qt::FindDirectChildrenOnly))
    {
        ret.insert(item->name(), QVariant::fromValue<DTwentyItem*>(item));
    }

    return ret;
}

DTwentyItemContainer *DTwentyItemContainer::valueSource() const
{
    return d->valueSource;
}

void DTwentyItemContainer::setValueSource(DTwentyItemContainer *valueSource)
{
    if (d->valueSource.data() == valueSource)
    {
        return;
    }

    d->valueSource = valueSource;
}
